﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TESTCommons.HttpHelper;
using TESTCommons.JsonHelper;
using TestDBData.EFContext;
using TestManage.Infrastructure.CustomAttribute;
using TestManage.Infrastructure.Extensions;
using TestModel.Configuration;
using TestModel.SysManage;

namespace TestManage.Controllers
{
    [AopActionFilter(true, false)]
    public class BaseController : Controller
    {
        #region 参数
        /// <summary>
        /// 帐户 信息 对象
        /// </summary>
        protected AccountModel _account = new AccountModel();
        /// <summary>
        /// 打印标题
        /// </summary>
        public string PrintTitle { get; set; } = "无标题";
        /// <summary>
        /// 初始化
        /// </summary>
        protected virtual void Init() { }
        #endregion

        #region 构造函数
        public BaseController()
        {
            this._account = WebHelper.GetSession<AccountModel>("session_account");
            this.Init();
        }
        #endregion

        public virtual IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public virtual IActionResult Info()
        {
            return View();
        }

        /// <summary>
        /// 导出EXCEL
        /// </summary>
        /// <param name="fc"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        //[HttpGet]
        //public virtual IActionResult ExportExcel(IFormCollection fc, int page = 1, int rows = 1000000)
        //{
        //    var query = this.FormCollectionToHashtable(fc);

        //    foreach (var item in Request.Query.Keys)
        //    {
        //        if (!fc.ContainsKey(item.ToString()))
        //            query.Add(item.ToString(), Request.Query[item].ToStr());
        //    }

        //    var _Headers = Tools.HttpHelper.Request.Headers;
        //    var url = _Headers.ContainsKey("Referer") ? _Headers["Referer"].ToStr() : "";
        //    if (!string.IsNullOrEmpty(url))
        //    {
        //        var dic = this.GetUrlQueryString(url);
        //        foreach (var item in dic)
        //        {
        //            if (!query.ContainsKey(item.Key)) query.Add(item.Key, item.Value);
        //        }
        //    }

        //    var pe = GetPagingEntity(query, page, rows);
        //    return File(DBToExcel(pe), Tools.GetFileContentType[".xls"].ToStr(), Guid.NewGuid().ToString() + ".xls");
        //}

        /// <summary>
        /// 表数据转换为EXCEL
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        [NonAction]
        //public virtual byte[] DBToExcel(PagingEntity pe)
        //{
        //    var dt = pe.Table;
        //    var list = pe.ColModel;
        //    HSSFWorkbook workbook = new HSSFWorkbook();
        //    ISheet sheet = workbook.CreateSheet();

        //    //填充表头
        //    IRow dataRow = sheet.CreateRow(0);
        //    foreach (DataColumn column in dt.Columns)
        //    {
        //        if (column.ColumnName.Equals("_ukid"))
        //            continue;
        //        foreach (var item in list)
        //        {
        //            if (column.ColumnName.Equals(item["field"].ToStr()))
        //            {
        //                dataRow.CreateCell(column.Ordinal).SetCellValue(item["title"].ToStr());
        //            }
        //        }
        //    }

        //    //填充内容
        //    for (int i = 0; i < dt.Rows.Count; i++)
        //    {
        //        dataRow = sheet.CreateRow(i + 1);
        //        for (int j = 0; j < dt.Columns.Count; j++)
        //        {
        //            if (dt.Columns[j].ColumnName.Equals("_ukid"))
        //                continue;
        //            dataRow.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
        //        }
        //    }

        //    //保存
        //    using (MemoryStream ms = new MemoryStream())
        //    {
        //        workbook.Write(ms);
        //        return ms.ToArray();
        //    }
        //}

        /// <summary>
        /// 打印
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public virtual IActionResult Print(DataTable dt)
        {
            TempData["Title"] = PrintTitle;
            var congfig = EngineContext.Current.Resolve<TestConfig>();
            return View(congfig.PrintPageUrl, dt);
        }

        /// <summary>
        /// 将  FormCollection  转换为  Dictionary
        /// </summary>
        /// <returns></returns>
        [NonAction]
        protected Hashtable FormCollectionToHashtable(IFormCollection fc)
        {
            var hashtable = new Hashtable();
            if (fc != null)
            {
                fc.Keys.ToList().ForEach(item =>
                {
                    hashtable.Add(item, System.Net.WebUtility.UrlDecode(fc[item]));
                });
            }
            return hashtable;
        }

        /// <summary>
        /// 根据地址字符串获取参数
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        [NonAction]
        public Dictionary<string, object> GetUrlQueryString(string Url)
        {
            var di = new Dictionary<string, object>();
            if (Url.Contains("?"))
            {
                Url = Url.Substring(Url.IndexOf("?") + 1);
                string[] str;
                if (Url.Contains("&"))
                {
                    str = Url.Split('&');
                    foreach (var item in str)
                    {
                        if (item.Contains("="))
                        {
                            di.Add(item.Split('=')[0], (item.Split('=')[1] == "null") ? null : item.Split('=')[1]);
                        }
                    }
                }
                else
                {
                    if (Url.Contains("="))
                    {
                        str = Url.Split('=');
                        di.Add(str[0], str[1]);
                    }
                }
            }
            return di;
        }

        /// <summary>
        /// 返回 Json 信息
        /// </summary>
        /// <param name="_object"></param>
        /// <returns></returns>
        public JsonResult Success(object obj, string mess)
        {
            if (obj == null)
            {
                return Json(new AjaxResult { type = ResultType.error, message = mess });
            }
            return Json(obj);
        }

        /// <summary>
        /// 处理上传文件
        /// </summary>
        /// <param name="_HttpPostedFileBase"></param>
        /// <param name="Format">文件格式</param>
        /// <param name="_WebRootPath"></param>
        /// <param name="Check">执行前 验证回调</param>
        /// <returns></returns>
        public string HandleUpFile(IFormFile _IFormFile, string[] Format, string _WebRootPath, Action<IFormFile> Check = null)
        {
            Check?.Invoke(_IFormFile);

            string ExtensionName = Path.GetExtension(_IFormFile.FileName).ToLower().Trim();//获取后缀名

            if (Format != null && !Format.Contains(ExtensionName.ToLower()))
            {
                return "请上传后缀名为：" + string.Join("、", Format) + " 格式的文件";
            }

            if (!Directory.Exists(_WebRootPath + "\\Content\\UpFile\\"))
                Directory.CreateDirectory(_WebRootPath + "\\Content\\UpFile\\");
            string filePath = "/Content/UpFile/" + Guid.NewGuid() + ExtensionName;
            // 创建新文件
            using (FileStream fs = System.IO.File.Create(_WebRootPath + filePath))
            {
                _IFormFile.CopyTo(fs);
                // 清空缓冲区数据
                fs.Flush();
            }
            return filePath;
        }
    }
}
